package com.study.spmongodb.book.wwj.char23;

/**
 * @author MI
 * @version 1.0
 * @date 2020/11/30 20:52
 */
public class CountDownLatch extends Latch {

    public CountDownLatch(int limit) {
        super(limit);
    }

    @Override
    public void await() throws InterruptedException {
        synchronized (this) {
            //当limit >0 ,当前线程进入阻塞状态
            while (limit > 0) {
                this.wait();
            }
        }
    }

    @Override
    public void countDown() throws IllegalAccessException {

        synchronized (this) {
            if (limit <= 0) {
                throw new IllegalAccessException(" all of task already arrived ");
            }
            // 使limit减一，并且通知阻塞线程
            limit--;
            this.notifyAll();
        }
    }

    @Override
    public int getUnarrived() {
        //返回还有多少任务未完成
        return limit;
    }

    public static void main(String[] args) throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(4);
        new ProgrammerTravel(latch, "Alex", "bus").start();
        new ProgrammerTravel(latch, "Gavin", "waking").start();
        new ProgrammerTravel(latch, "Jack", "SubWAY").start();
        new ProgrammerTravel(latch, "Dillon", "Bicycle").start();

        latch.await();
        System.out.println("all of programmer arrived==");

    }
}
